package com.football.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.football.springboot.common.Constants;
import com.football.springboot.common.RoleEnum;
import com.football.springboot.controller.dto.UserDTO;
import com.football.springboot.controller.dto.UserPasswordDTO;
import com.football.springboot.entity.Menu;
import com.football.springboot.entity.User;
import com.football.springboot.exception.ServiceException;
import com.football.springboot.mapper.RoleMapper;
import com.football.springboot.mapper.RoleMenuMapper;
import com.football.springboot.mapper.UserMapper;
import com.football.springboot.service.IMenuService;
import com.football.springboot.service.UserService;
import com.football.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService {

    private static final Log LOG = Log.get();

    @Resource
    UserMapper userMapper;

    @Resource
    RoleMapper roleMapper;

    @Resource
    RoleMenuMapper roleMenuMapper;

    @Resource
    IMenuService menuService;

    //登录
    @Override
    public UserDTO login(UserDTO userDto) {
        // 用户密码 md5加密
        userDto.setPassword(SecureUtil.md5(userDto.getPassword()));
        User user = getUserInfo(userDto);
        //System.out.println(user.toString());
        if (user != null) {
            BeanUtil.copyProperties(user, userDto, true);//拷贝user用户信息
            // 设置token
            String token = TokenUtils.genToken(user.getId().toString(), user.getPassword());
            userDto.setToken(token);
            String role = user.getRole(); // 查看用户的权限角色

            // 设置用户的菜单列表
            List<Menu> roleMenus = getRoleMenus(role);

            userDto.setMenus(roleMenus);
            return userDto;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }
    }

    //注册
    @Override
    public User register(UserDTO userDTO) {
        // 用户密码 md5加密
        userDTO.setPassword(SecureUtil.md5(userDTO.getPassword()));
        User user = getUserInfo(userDTO);
        if (user == null) {
            user = new User();
            BeanUtil.copyProperties(userDTO, user, true);
            // 默认一个普通用户的角色
            user.setRole(RoleEnum.ROLE_COMMON.toString());
            if (user.getNickname() == null) {
                user.setNickname(user.getUsername());
            }
            save(user);  // 把 copy完之后的用户对象存储到数据库
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return user;
    }


    //修改密码
    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        int update = userMapper.updatePassword(userPasswordDTO);
        if (update < 1) {
            throw new ServiceException(Constants.CODE_600, "密码错误");
        }
    }

    //获取用户详细信息
    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User user;
        try {
            user = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return user;
    }

    //获取当前用户的菜单列表
    private List<Menu> getRoleMenus(String roleFlag) {
        //根据角色唯一标识flag查找角色id
        Integer roleId = roleMapper.selectByFlag(roleFlag);
        // 根据角色id 通过rolemenu表查找当前角色的所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);

        // 查出系统所有的菜单(树形)
        List<Menu> menus = menuService.findMenus("");
        // 最后筛选完成之后的list
        List<Menu> roleMenus = new ArrayList<>();
        // 筛选当前用户角色的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            // removeIf()  移除 children 里面不在 menuIds集合中的 元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }
}
